package com.tedu.springmvc2.controller;

import com.tedu.springmvc2.mapper.UserMapper;
import com.tedu.springmvc2.pojo.dto.UserDTO;
import com.tedu.springmvc2.pojo.dto.UserUpdateDTO;
import com.tedu.springmvc2.pojo.entity.User;
import com.tedu.springmvc2.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/users")
public class RestfulUserController {

    @Autowired
    private UserMapper userMapper;


//    @RequestMapping(value = "/users",method = RequestMethod.POST)
    @PostMapping
    public String add(UserDTO userDTO){
        System.out.println("注册");
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return "成功";
    }

//    @RequestMapping(value = "/users",method = RequestMethod.PUT)
    @PutMapping
    public String update(UserUpdateDTO userUpdateDTO){
        User user = new User();
        BeanUtils.copyProperties(userUpdateDTO,user);
        int num = userMapper.updateById(user);
        return num>0?"成功":"失败";
    }

//    @RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id){
        System.out.println("删除"+id);
        int num = userMapper.deleteById(id);
        return num>0?"成功":"失败";
    }

//    @RequestMapping(value = "/users",method = RequestMethod.GET)
    @GetMapping
    public List<UserVO> findAll(){
        return userMapper.selectAll();
    }
//  @RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
    @GetMapping("/{id}")
    public UserVO findById(@PathVariable Integer id){
        return userMapper.selectById(id);
    }

}
